<template>
    <div>
        <div class="flex_between">
            <span class="ml5 bold font_size14" style="position: relative;top: 5px;"> {{ title }} </span>
            <el-button type="primary" size="mini" @click="openGoods">选择{{ typeText }}</el-button>
        </div>
        <div class="basc-info-card mt10" v-if="vList && vList.length > 0">
            <div class="flex_row" v-for="(item, gindex) in vList" :key="gindex">
                <div class="mb-box-cell flex1">
                    <div class="flex_between">
                        <div class="flex_row" style="width: 40%;overflow: hidden;">
                            <div class="obj-gdimg-box">
                                <img :src="item.img" alt="" class="obj-avatar">
                            </div>
                            <div class="ml10" style="flex: 1;overflow: hidden;">
                                <div class="bold font_size14" style="max-width: 100%;">{{ item.gdname }}</div>
                                <div class="font_size12">{{ item.spec_title }}</div>
                            </div>
                        </div>
                        <div style="flex: 1;justify-items: flex-end;">
                            <div class="obj-info">
                                <div class="price-input-row flex_row">
                                    <div class="price-input-item">
                                        <span class="mr5">活动价:</span>
                                        <el-input-number v-model="item.price" :precision="2" :step="1" :min="0"
                                            size="small" controls-position="right"
                                            @change="onPriceChange(gindex, 'price', $event)"
                                            @input="onPriceChange(gindex, 'price', $event)" class="price-input">
                                        </el-input-number>
                                    </div>
                                    <div class="price-input-item">
                                        <span class="mr5">划线价:</span>
                                        <el-input-number v-model="item.pricec" :precision="2" :step="1" :min="0"
                                            size="small" controls-position="right"
                                            @change="onPriceChange(gindex, 'pricec', $event)"
                                            @input="onPriceChange(gindex, 'pricec', $event)" class="price-input">
                                        </el-input-number>
                                    </div>
                                    <div class="price-input-item">
                                        <span class="mr5">数量:</span>
                                        <el-input-number v-model="item.number" :min="0" size="small"
                                            controls-position="right" @change="onPriceChange(gindex, 'number', $event)"
                                            @input="onPriceChange(gindex, 'number', $event)" class="number-input">
                                        </el-input-number>
                                        <span v-if="item.unit_title" class="ml5">({{ item.unit_title || '' }})</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="del-box ml5" @click="removeGoods(gindex)">
                    <i class="el-icon-delete-solid"></i>
                </div>
            </div>
        </div>
        <el-empty v-else :description="`请选择${typeText}`" :image-size="80"></el-empty>
        <div class="total-summary-box" v-if="vList && vList.length > 0">
            <div class="total-item">
                <span class="total-label">累计金额</span>
                <span class="total-amount">￥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="total-divider"></div>
            <div class="total-item">
                <span class="total-label">合计数量</span>
                <span class="total-quantity">{{ totalNumber }}</span>
            </div>
        </div>
        <!-- 选择产品 -->
        <chiceGoodList ref="chiceGoodListRef" @determineFun="chooseGoods"></chiceGoodList>
        <!-- 选择项目 -->
        <chiceProject ref="chiceProjectRef" @determineFun="chooseProject"></chiceProject>
    </div>
</template>

<script setup>
import { watch, computed, defineProps, defineEmits, ref, getCurrentInstance, nextTick } from '@vue/composition-api';
import chiceGoodList from "@/components/commV2/chiceSku/chiceGoodList.vue"
import chiceProject from "@/components/commV2/chiceSku/chiceProject.vue"

const { proxy } = getCurrentInstance()

const props = defineProps({
    // 标题 
    title: {
        type: [String, Number],
        default: '商品',
    },
    list: {
        type: Array,
        default: () => ([])
    },
    idyun: {
        type: [String, Number],
        default: '',
    },
    type: {
        type: String,
        default: 'goods',
    },
});

const typeText = computed(() => {
    return props.type === 'goods' ? '商品' : '项目'
})

const vList = ref([])
watch(() => props.list, (newVal) => {
    vList.value = newVal || []
}, {
    deep: true,
    immediate: true
})

const emit = defineEmits(['load-more', 'item-change', 'selected']);
const totalPrice = computed(() => {
    return vList.value.reduce((sum, item) => sum + item.price * item.number, 0)
})
const totalNumber = computed(() => {
    return vList.value.reduce((sum, item) => sum + item.number, 0)
})
// 处理价格或数量变化
const onPriceChange = async (index, field, value) => {
    // 确保 value 是有效的数字
    if (value === null || value === undefined) {
        return;
    }
    // 创建新的数组和对象来确保响应式更新
    const newList = vList.value.map((item, i) => {
        if (i === index) {
            return {
                ...item,
                [field]: value
            };
        }
        return item;
    });
    // 更新响应式数据
    vList.value = newList;
    // 等待下一个 tick 确保 DOM 已更新
    await nextTick();
    // 向父组件发送整个列表
    emit('item-change', vList.value);
};

// 处理选择产品
const chiceGoodListRef = ref(null)
const chiceProjectRef = ref(null)
const openGoods = () => {
    console.log("openGoods：", props.type)
    if (!props.idyun) return proxy.$message.error("请选择云店")
    if (props.type === 'goods') {
        if (chiceGoodListRef.value) {
            chiceGoodListRef.value.initData({
                shopid_yd: props.idyun,
            })
            chiceGoodListRef.value.dialogVisible = true
        }
    } else {
        if (chiceProjectRef.value) {
            chiceProjectRef.value.initData()
            chiceProjectRef.value.popProjectFilling_Show = true
        }
    }
};

const removeGoods = (gindex) => {
    proxy.$confirm('确定删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        vList.value.splice(gindex, 1)
        emit('item-change', vList.value)
    })
}

// 选择商品后的回调
const chooseGoods = (selectedGoods) => {
    console.log("selectedGoods：", selectedGoods)
    let newList = []
    selectedGoods.map((v) => {
        newList.push({
            ...v,
            gdname: v.gd_title,
            spec_title: v.doc,
            unitid: v.unit_id,
            unit_title: v.title,
        })
    })
    vList.value = [...newList, ...vList.value]
    // 向父组件发送选择的商品数据
    emit('selected', newList);
};

// 选择项目后的回调
const chooseProject = (selectedProject) => {
    console.log("selectedProject：", selectedProject)
    vList.value = [...vList.value, selectedProject]
    // 向父组件发送选择的商品数据
    emit('selected', vList.value);
}

</script>

<style lang="scss" scoped>
div {
    line-height: 1.5 !important;
}

.basc-info-card {
    box-sizing: border-box;
    overflow: hidden;
    padding: 0 12px;
    border-radius: 8px 8px 0 0;
    border: 1px solid #e2e8f0;
}

.mb-box-cell {
    box-sizing: border-box;
    overflow: hidden;
    padding: 12px 0;
    border-bottom: 1px solid #e2e8f0;
}

/* 修复最后一个元素的边框问题 */
.flex_row:last-child .mb-box-cell {
    border-bottom: 0 !important;
}

.obj-ls-box {
    margin-bottom: 10px;
    border-bottom: 1px solid #e9ecef;
    padding-bottom: 10px;
}

.obj-ls-box:last-child {
    margin-bottom: 0 !important;
    padding-bottom: 0 !important;
    border-bottom: none !important;
}

.obj-gdimg-box {
    height: 40px;
    width: 40px;
    border-radius: 2px;
    border: 1px solid #f5f9f9;
    overflow: hidden;
    background-color: #f5f9f9;
}

.obj-avatar {
    height: 100%;
    width: 100%;
    border-radius: 6px;
}

.price-input-row {
    display: flex;
    flex-direction: row;
    gap: 20px;
}

.price-input-item {
    display: flex;
    align-items: center;
    font-size: 12px;
}

.price-input,
.number-input {
    width: 120px;
}

::v-deep .el-input-number {
    .el-input__inner {
        padding-left: 8px;
        padding-right: 30px;
    }
}

::v-deep .el-input-number--mini {
    .el-input__inner {
        height: 24px;
        line-height: 24px;
    }

    .el-input-number__increase,
    .el-input-number__decrease {
        height: 12px;
        line-height: 12px;
    }
}

.del-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: #e9f1f1;
    cursor: pointer;
    font-size: 14px;
    color: #f56c6c;
    margin-left: 10px;
}

::v-deep .el-empty {
    padding: 20px 0 0 !important;
}

.total-summary-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 6px 14px;
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
    border-radius: 0 0 12px 12px;
    border: 1px solid #e2e8f0;
    border-top: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.total-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.total-label {
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
}

.total-amount {
    font-size: 18px;
    font-weight: 700;
    color: #e11d48;
    text-shadow: 0 1px 2px rgba(225, 29, 72, 0.1);
}

.total-quantity {
    font-size: 16px;
    font-weight: 600;
    color: #0f172a;
}

.total-divider {
    width: 1px;
    height: 24px;
    background-color: #cbd5e1;
    margin: 0 24px;
}
</style>